<template>
  <div class="detail-page">
    <a-row :gutter="16">
      <a-col :span="24">
        <a-page-header
          :title="houseInfo.title"
          :sub-title="houseInfo.cityName ? `${houseInfo.cityName} · ${houseInfo.district}` : '加载中...'"
          @back="goBack"
        />
      </a-col>
    </a-row>
    
    <a-row :gutter="16" style="margin-top: 16px">
      <a-col :span="16">
        <a-card :bordered="false" :loading="loading">
          <a-row :gutter="16">
            <a-col :span="12">
              <img :src="houseInfo.image" alt="房源图片" class="house-image" />
            </a-col>
            <a-col :span="12">
              <div class="house-info">
                <h2 class="price">{{ houseInfo.price?.totalPriceText }}</h2>
                <p class="unit-price">{{ houseInfo.price?.unitPriceText }}</p>
                
                <a-divider />
                
                <a-descriptions title="基本信息" :column="1">
                  <a-descriptions-item label="户型">{{ houseInfo.layout }}</a-descriptions-item>
                  <a-descriptions-item label="面积">{{ houseInfo.area }}</a-descriptions-item>
                  <a-descriptions-item label="朝向">{{ houseInfo.orientation }}</a-descriptions-item>
                  <a-descriptions-item label="装修">{{ houseInfo.decoration }}</a-descriptions-item>
                  <a-descriptions-item label="楼层">{{ houseInfo.floor }}</a-descriptions-item>
                  <a-descriptions-item label="建筑年代">{{ houseInfo.buildYear }}</a-descriptions-item>
                  <a-descriptions-item label="建筑类型">{{ houseInfo.buildType }}</a-descriptions-item>
                </a-descriptions>
                
                <a-divider />
                
                <div class="action-buttons">
                  <a-button type="primary" @click="addToComparison">加入对比</a-button>
                  <a-button @click="openOriginalLink">查看原始链接</a-button>
                </div>
              </div>
            </a-col>
          </a-row>
          
          <a-divider />
          
          <a-tabs default-active-key="1">
            <a-tab-pane key="1" tab="房源详情">
              <div class="detail-content">
                <h3>房源描述</h3>
                <p>{{ houseInfo.description || '暂无描述' }}</p>
                
                <h3>周边配套</h3>
                <a-row :gutter="16">
                  <a-col :span="8">
                    <a-card title="交通">
                      <p>{{ houseInfo.transportation || '暂无信息' }}</p>
                    </a-card>
                  </a-col>
                  <a-col :span="8">
                    <a-card title="教育">
                      <p>{{ houseInfo.education || '暂无信息' }}</p>
                    </a-card>
                  </a-col>
                  <a-col :span="8">
                    <a-card title="医疗">
                      <p>{{ houseInfo.medical || '暂无信息' }}</p>
                    </a-card>
                  </a-col>
                </a-row>
              </div>
            </a-tab-pane>
            <a-tab-pane key="2" tab="价格分析">
              <div class="price-analysis">
                <h3>价格评估</h3>
                <a-row :gutter="16">
                  <a-col :span="8">
                    <a-statistic
                      title="同区域均价"
                      :value="priceAnalysis.districtAvgPrice"
                      :precision="2"
                      suffix="万元/㎡"
                    />
                  </a-col>
                  <a-col :span="8">
                    <a-statistic
                      title="价格差异"
                      :value="priceAnalysis.priceDiff"
                      :precision="2"
                      :value-style="{ color: priceAnalysis.priceDiff >= 0 ? '#cf1322' : '#3f8600' }"
                      :prefix="priceAnalysis.priceDiff >= 0 ? <arrow-up-outlined /> : <arrow-down-outlined />"
                      suffix="%"
                    />
                  </a-col>
                  <a-col :span="8">
                    <a-statistic
                      title="价格评估"
                      :value="priceAnalysis.evaluation"
                    />
                  </a-col>
                </a-row>
                
                <a-divider />
                
                <h3>周边房源价格对比</h3>
                <div ref="priceCompareChartRef" style="width: 100%; height: 300px"></div>
              </div>
            </a-tab-pane>
            <a-tab-pane key="3" tab="位置信息">
              <div class="location-info">
                <h3>位置</h3>
                <p>{{ houseInfo.location }}</p>
                <div id="map-container" style="width: 100%; height: 400px"></div>
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>
      
      <a-col :span="8">
        <a-card title="推荐房源" :bordered="false" :loading="loading">
          <a-list
            :data-source="recommendHouses"
            :pagination="false"
            item-layout="horizontal"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #title>
                    <router-link :to="`/detail/${item.id}`">{{ item.title }}</router-link>
                  </template>
                  <template #description>
                    <div>{{ item.layout }} | {{ item.area }} | {{ item.decoration }}</div>
                    <div class="recommend-price">{{ item.price?.totalPriceText }}</div>
                  </template>
                  <template #avatar>
                    <a-avatar shape="square" :size="64" :src="item.image" />
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
        
        <a-card title="价格走势" :bordered="false" style="margin-top: 16px" :loading="loading">
          <div ref="priceTrendChartRef" style="width: 100%; height: 200px"></div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useHouseStore } from '../stores/houseStore'
import { useAnalysisStore } from '../stores/analysisStore'
import { message } from 'ant-design-vue'
import * as echarts from 'echarts'
import { ArrowUpOutlined, ArrowDownOutlined } from '@ant-design/icons-vue'

const route = useRoute()
const router = useRouter()
const houseStore = useHouseStore()
const analysisStore = useAnalysisStore()

// 状态
const loading = ref(false)
const houseInfo = ref({})
const recommendHouses = ref([])
const priceAnalysis = reactive({
  districtAvgPrice: 0,
  priceDiff: 0,
  evaluation: '暂无评估'
})

// 图表引用
const priceCompareChartRef = ref(null)
const priceTrendChartRef = ref(null)

// 图表实例
let priceCompareChart = null
let priceTrendChart = null

// 返回上一页
const goBack = () => {
  router.back()
}

// 加入对比
const addToComparison = () => {
  message.success('已加入对比列表')
  // 实际实现可以存储到store或localStorage中
}

// 打开原始链接
const openOriginalLink = () => {
  if (houseInfo.value.link) {
    window.open(houseInfo.value.link, '_blank')
  } else {
    message.warning('原始链接不可用')
  }
}

// 获取房源详情
const fetchHouseDetail = async () => {
  const id = route.params.id
  if (!id) {
    message.error('房源ID不存在')
    router.push('/')
    return
  }
  
  loading.value = true
  
  try {
    // 获取房源详情
    const detail = await houseStore.getHouseDetail(id)
    houseInfo.value = detail
    
    // 获取推荐房源
    const recommend = await houseStore.getRecommendHouses(id)
    recommendHouses.value = recommend
    
    // 获取价格分析
    const analysis = await analysisStore.getHousePriceAnalysis(id)
    priceAnalysis.districtAvgPrice = analysis.districtAvgPrice
    priceAnalysis.priceDiff = analysis.priceDiff
    priceAnalysis.evaluation = analysis.evaluation
    
    // 更新图表
    nextTick(() => {
      initPriceCompareChart(analysis.nearbyHouses)
      initPriceTrendChart(analysis.priceTrend)
    })
    
    // 初始化地图
    nextTick(() => {
      initMap()
    })
  } catch (error) {
    console.error('获取房源详情失败:', error)
    message.error('获取房源详情失败')
  } finally {
    loading.value = false
  }
}

// 初始化周边房源价格对比图表
const initPriceCompareChart = (data) => {
  if (!priceCompareChartRef.value) return
  
  priceCompareChart = echarts.init(priceCompareChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['总价', '单价']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: data.map(item => item.title.substring(0, 6) + '...'),
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '总价(万元)',
        position: 'left'
      },
      {
        type: 'value',
        name: '单价(万元/㎡)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '总价',
        type: 'bar',
        data: data.map(item => item.totalPrice),
        itemStyle: {
          color: '#1890ff'
        }
      },
      {
        name: '单价',
        type: 'line',
        yAxisIndex: 1,
        data: data.map(item => item.unitPrice),
        smooth: true,
        lineStyle: {
          color: '#fa8c16'
        },
        itemStyle: {
          color: '#fa8c16'
        }
      }
    ]
  }
  
  priceCompareChart.setOption(option)
}

// 初始化价格趋势图表
const initPriceTrendChart = (data) => {
  if (!priceTrendChartRef.value) return
  
  priceTrendChart = echarts.init(priceTrendChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.map(item => item.date)
    },
    yAxis: {
      type: 'value',
      name: '单价(万元/㎡)'
    },
    series: [
      {
        name: '价格趋势',
        type: 'line',
        data: data.map(item => item.price),
        smooth: true,
        lineStyle: {
          color: '#1890ff',
          width: 2
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(24, 144, 255, 0.3)'
              },
              {
                offset: 1,
                color: 'rgba(24, 144, 255, 0.1)'
              }
            ]
          }
        }
      }
    ]
  }
  
  priceTrendChart.setOption(option)
}

// 初始化地图
const initMap = () => {
  // 这里可以根据实际情况集成高德地图或百度地图
  // 示例代码仅作参考
  if (window.AMap && houseInfo.value.latitude && houseInfo.value.longitude) {
    const map = new window.AMap.Map('map-container', {
      zoom: 15,
      center: [houseInfo.value.longitude, houseInfo.value.latitude]
    })
    
    const marker = new window.AMap.Marker({
      position: [houseInfo.value.longitude, houseInfo.value.latitude],
      title: houseInfo.value.title
    })
    
    map.add(marker)
  }
}

// 监听窗口大小变化，重绘图表
window.addEventListener('resize', () => {
  priceCompareChart?.resize()
  priceTrendChart?.resize()
})

// 页面加载时获取数据
onMounted(() => {
  fetchHouseDetail()
})
</script>

<style scoped lang="scss">
.detail-page {
  padding: 24px;
  
  .house-image {
    width: 100%;
    border-radius: 4px;
  }
  
  .house-info {
    .price {
      font-size: 24px;
      color: #f5222d;
      margin-bottom: 8px;
    }
    
    .unit-price {
      font-size: 16px;
      color: #666;
    }
    
    .action-buttons {
      display: flex;
      gap: 16px;
    }
  }
  
  .detail-content {
    h3 {
      margin-top: 24px;
      margin-bottom: 16px;
      font-size: 18px;
    }
  }
  
  .price-analysis {
    h3 {
      margin-top: 24px;
      margin-bottom: 16px;
      font-size: 18px;
    }
  }
  
  .recommend-price {
    color: #f5222d;
    font-weight: bold;
    margin-top: 4px;
  }
}
</style>